/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> neighbors;
    Node() {
        val = 0;
        neighbors = vector<Node*>();
    }
    Node(int _val) {
        val = _val;
        neighbors = vector<Node*>();
    }
    Node(int _val, vector<Node*> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};
*/

class Solution {
public:
    std::unordered_map<Node*, Node*> visited;  // 存储已经访问过的结点与其副本的映射表
    Node* cloneGraph(Node* node) {
        return dfs(node);
    }
    Node* dfs(Node* node) {
        if (node == nullptr) return nullptr;
        if (visited.count(node)) return visited[node];

        Node* newNode = new Node(node->val);
        visited[node] = newNode;
        for (Node* neighbor : node->neighbors) {
            newNode->neighbors.push_back(dfs(neighbor));
        }
        return newNode;
    }
};